<?php

namespace App\Service;

use Elasticsearch\Client;
use Hyperf\Elasticsearch\ClientBuilderFactory;
use Hyperf\Utils\ApplicationContext;

/**
 *
 */
class ElasticSearch
{

    /**
     * @var
     */
    protected $container;

    public $es_client;

    public function __construct()
    {
        $this->container = ApplicationContext::getContainer();

        // 如果在协程环境下创建，则会自动使用协程版的 Handler，非协程环境下无改变
        $builder = $this->container->get(ClientBuilderFactory::class)->create();
        $this->es_client = $builder->setBasicAuthentication("elastic","pjyz@123")->setHosts([env('ELASTICSEARCH_HOST','http://elastic:fft&202220@114.55.15.57:9200')])->build();

    }

    /**
     * 创建index - 相当于MySQL的数据库
     * @param string $index
     * @return array
     */
    public function createIndex(string $index): array
    {
        $params = [
            'index' => $index,
        ];
        return $this->es_client->indices()->create($params);
    }

    /**
     * 设置mapping
     * @param $params
     * @return array
     */
    public function putMapping($params): array
    {
        return $this->es_client->indices()->putMapping($params);
    }

    /**
     * 获取mapping
     * @param $params
     * @return array
     */
    public function getMapping($params): array
    {
        return $this->es_client->indices()->getMapping($params);
    }

    /**
     * 判断索引是否存在
     * @param string $index
     * @return bool
     */
    public function indexExistsEs(string $index): bool
    {
        $params = [
            'index' => $index,
        ];
        return $this->es_client->indices()->exists($params);
    }

    /**
     * 删除索引
     * @param string $index
     * @return array|callable
     */
    public function deleteIndex(string $index)
    {
        $params = [
            'index' => $index
        ];
        return $this->es_client->indices()->delete($params);
    }

    /**
     * 创建文档
     * @param array $params
     * @return array|callable
     */
    public function indexEs(array $params)
    {
        $index_data = [
            'index' => $params['index'],
            'body' => $params['body'],
        ];
        return $this->es_client->index($index_data);
    }

    /**
     * 批量创建文档
     * @param array $params
     * @return callable|array
     */
    public function bulk(array $params)
    {
        return $this->es_client->bulk($params);
    }

    /**
     * 更新文档
     * @param array $params
     * $params = [
     *      'index' => 'chat_data',
     *       'id' => '文档id',
     *       'doc' => [
     *          '字段名1' => '要修改的值',
     *          '字段名2' => '要修改的值',
     *          '字段名3' => '要修改的值',
     *       ]
     * ]
     * @return array|callable
     */
    public function update(array $params)
    {
        $params = [
            'index' => $params['index'],
            'id' => $params['id'],
            'body' => [
                'doc' => $params['doc']
            ]
        ];
        return $this->es_client->update($params);
    }

    /**
     * 删除文档
     * @param $params
     * @return array|callable
     */
    public function deleteEs($params)
    {
        extract($params);
        $delete_data = [
            'index' => $index,
            'type' => $type,
            'id' => $id,
        ];
        return $this->es_client->delete($delete_data);
    }

    /**
     * @param array $params
     * @return array|callable
     */
    public function count(array $params)
    {
        $search = $params['search'];
        $params = [
            'index' => $params['index']
        ];
        // 只有一个搜索字段时
        if (count($search) == 1) {
            $query = [
                'match_phrase' => $search
            ];
        } else {
            $must = [];
            foreach ($search as $k => $v) {
                // 一定要把时间筛选弄出来，因为这里的条件类似where('xxxx','xxxx')
                if(!in_array($k,['start_time','end_time'])) {
                    $must[] = ['match' => [$k => $v]];
                }
            }
            $query['bool']['should'] = $must;
            // 时间搜索
            if(!empty($search['start_time'])) {
                $filter = [
                    'range' => [
                        'start_time' =>[
                            'gte' => $search['start_time'],
                            'lte' => $search['end_time']
                        ]
                    ]
                ];
                $query['bool']['filter'] = $filter;
            }
        }
        $params['body'] = [
            'query' => $query
        ];
        return $this->es_client->count($params);
    }

    /**
     * es搜索数据
     * @param array $params
     * @param int $page
     * @param int $size
     * @return array|callable
     */
    public function search(array $params, int $page = 1, int $size = 15)
    {
        $search = $params['search'];
        $params = [
            'index' => $params['index'],
            'from' => ($page <= 0) ? 0 : $page - 1,
            'size' => $size
        ];
        // 只有一个搜索字段时
        if (count($search) == 1) {
            $query = [
                'match_phrase' => $search
            ];
        } else {
            $must = [];
            foreach ($search as $k => $v) {
                // 一定要把时间筛选弄出来，因为这里的条件类似where('xxxx','xxxx')
                if(!in_array($k,['start_time','end_time'])) {
                    $must[] = ['match' => [$k => $v]];
                }
            }
            $query['bool']['should'] = $must;
            // 时间搜索
            if(!empty($search['start_time'])) {
                $filter = [
                    'range' => [
                        'start_time' =>[
                            'gte' => $search['start_time'],
                            'lte' => $search['end_time']
                        ]
                    ]
                ];
                $query['bool']['filter'] = $filter;
            }
        }
        $params['body'] = [
            'query' => $query,
            'sort'  => [
                [
                    'time_stamp' => 'desc'
                ]
            ],
        ];
        return $this->es_client->search($params);
    }
}